package com.filemanager;

import com.filemanager.exceptions.ChangeDirectoryException;
import com.filemanager.exceptions.DirectoryCreationException;
import com.filemanager.exceptions.FileCreationException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

/**
 * User: vsinjavin
 * Date: 11/15/13
 */
public class FileManagerImpl implements FileManager {

    private String currentDirectory;

    public FileManagerImpl() {
        currentDirectory = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        currentDirectory.substring(0, currentDirectory.lastIndexOf("/"));
    }


    @Override
    public void changeDirectory(String path) throws ChangeDirectoryException {
        File file = new File(path);

        if (file.isAbsolute()) {
            if (!file.isDirectory())
                throw new ChangeDirectoryException("Error! Can't change directory!");
            currentDirectory = path;
        } else if (path.equals("..")) {
            currentDirectory = new File(currentDirectory).getParent();
        } else {
            currentDirectory = currentDirectory + "/" + path;
        }
    }

    @Override
    public void createFile(String fileName) throws FileCreationException {
        File file = new File(currentDirectory + fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new FileCreationException(String.format("Can't create file with name: %s", fileName), e);
        }
    }

    @Override
    public void createDirectory(String directoryName) throws DirectoryCreationException {
        boolean success = (new File(currentDirectory + directoryName)).mkdir();

        if (!success)
            throw new DirectoryCreationException(String.format("Can't create directory with name: %s", directoryName));
    }

    @Override
    public Collection<File> getDirectoryStructure() {
        return getDirectoryStructure(currentDirectory);
    }

    @Override
    public Collection<File> getDirectoryStructure(String path) {

        File[] filesAndFolders = new File(path).listFiles();

        if (filesAndFolders != null)
            return new ArrayList<File>(Arrays.asList(filesAndFolders));

        return Collections.emptyList();
    }

    @Override
    public String currentPath() {
        return currentDirectory;
    }

}
